<!--
  今日记录查看组件
  创建时间：2025-09-11
  作者：开发团队
  目的：查看当日核验记录列表
-->

<template>
  <div class="today-records">
    <el-card class="records-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div>
            <h2>今日记录</h2>
            <p>查看今日核验记录统计和详细列表</p>
          </div>
          <div class="header-actions">
            <el-button
              type="primary"
              :loading="loading"
              @click="refreshData"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计概览 -->
      <div class="statistics-section">
        <el-row :gutter="16" class="stats-row">
          <el-col :span="6">
            <el-statistic
              title="总核验数"
              :value="statistics.total_verifications"
              class="stat-item"
            >
              <template #suffix>
                <span class="stat-suffix">次</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="通过数"
              :value="statistics.pass_count"
              class="stat-item stat-success"
            >
              <template #suffix>
                <span class="stat-suffix">次</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="拒绝数"
              :value="statistics.reject_count"
              class="stat-item stat-danger"
            >
              <template #suffix>
                <span class="stat-suffix">次</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="我的核验"
              :value="statistics.my_verifications"
              class="stat-item stat-warning"
            >
              <template #suffix>
                <span class="stat-suffix">次</span>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
      </div>
      
      <!-- 筛选器 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-select
              v-model="filterStatus"
              placeholder="核验结果"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="全部" value="" />
              <el-option label="通过" value="pass" />
              <el-option label="拒绝" value="reject" />
            </el-select>
          </el-col>
          <el-col :span="16">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索访客姓名或手机号"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </div>
      
      <!-- 记录列表 -->
      <div class="records-section">
        <el-table
          v-loading="loading"
          :data="paginatedRecords"
          stripe
          class="records-table"
        >
          <el-table-column prop="visitor_name" label="访客姓名" width="120" />
          
          <el-table-column prop="visitor_phone" label="手机号" width="140" />
          
          <el-table-column prop="host_name" label="被访人" width="120" />
          
          <el-table-column prop="verification_time" label="核验时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.verification_time) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="result" label="核验结果" width="100">
            <template #default="{ row }">
              <el-tag
                :type="row.result === 'pass' ? 'success' : 'danger'"
                size="small"
              >
                {{ row.result === 'pass' ? '通过' : '拒绝' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="guard_name" label="门卫" width="100" />
          
          <el-table-column prop="is_special" label="特殊访客" width="100">
            <template #default="{ row }">
              <el-tag
                v-if="row.is_special"
                type="warning"
                size="small"
                round
              >
                {{ row.special_type }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                text
                size="small"
                @click="showRecordDetail(row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
          
          <template #empty>
            <el-empty description="暂无记录" />
          </template>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="totalRecords"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 记录详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="核验记录详情"
      width="600px"
    >
      <div v-if="selectedRecord" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="访客姓名">
            {{ selectedRecord.visitor_name }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ selectedRecord.visitor_phone }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            {{ selectedRecord.visitor_id_card || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="公司">
            {{ selectedRecord.company || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="被访人">
            {{ selectedRecord.host_name }}
          </el-descriptions-item>
          <el-descriptions-item label="被访人电话">
            {{ selectedRecord.host_phone }}
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ formatDateTime(selectedRecord.visit_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="访问事由">
            {{ selectedRecord.purpose }}
          </el-descriptions-item>
          <el-descriptions-item label="核验时间">
            {{ formatDateTime(selectedRecord.verification_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="核验结果">
            <el-tag
              :type="selectedRecord.result === 'pass' ? 'success' : 'danger'"
            >
              {{ selectedRecord.result === 'pass' ? '通过' : '拒绝' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedRecord.rejection_reason" label="拒绝原因" :span="2">
            {{ selectedRecord.rejection_reason }}
          </el-descriptions-item>
          <el-descriptions-item label="特殊访客">
            <el-tag
              v-if="selectedRecord.is_special"
              type="warning"
              round
            >
              {{ selectedRecord.special_type }}
            </el-tag>
            <span v-else>否</span>
          </el-descriptions-item>
          <el-descriptions-item label="核验门卫">
            {{ selectedRecord.guard_name }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watchEffect } from 'vue'
import { showError, showSuccess } from '@/utils/message'
import { Refresh, Search } from '@element-plus/icons-vue'
import { verificationApi } from '@/api/verification'
import { useAuthStore } from '@/stores/auth'
import type {
  VerificationRecord,
  TodayStatistics,
  VerificationRecordsParams
} from '@/types/verification'
import { formatDateTime, getTodayDate } from '@/utils/date'

// 状态管理
const authStore = useAuthStore()

// 响应式状态
const loading = ref(false)
const records = ref<VerificationRecord[]>([])
const statistics = ref<TodayStatistics>({
  total_verifications: 0,
  pass_count: 0,
  reject_count: 0,
  special_visitor_count: 0,
  my_verifications: 0
})

// 筛选和搜索
const filterStatus = ref('')
const searchKeyword = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const selectedRecord = ref<VerificationRecord | null>(null)

// 计算属性：过滤后的记录（不包含副作用）
const filteredRecords = computed(() => {
  let filtered = records.value
  
  // 按状态筛选
  if (filterStatus.value) {
    filtered = filtered.filter(record => record.result === filterStatus.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(record => 
      record.visitor_name.toLowerCase().includes(keyword) ||
      record.visitor_phone.includes(keyword)
    )
  }
  
  return filtered
})

// 计算属性：分页显示的记录
const paginatedRecords = computed(() => {
  const filtered = filteredRecords.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 监听过滤结果变化，更新总记录数
watchEffect(() => {
  totalRecords.value = filteredRecords.value.length
})

/**
 * 加载今日记录
 */
const loadTodayRecords = async (): Promise<void> => {
  try {
    loading.value = true
    
    const params: VerificationRecordsParams = {
      start_date: getTodayDate(),
      end_date: getTodayDate(),
      page: 1,
      size: 1000 // 获取全部记录，前端分页
    }
    
    const response = await verificationApi.getRecords(params)
    records.value = response.items || []
    
  } catch (error) {
    console.error('加载今日记录失败:', error)
    showError('加载记录失败')
    
    // 开发阶段：使用模拟数据
    records.value = generateMockRecords()
  } finally {
    loading.value = false
  }
}

/**
 * 加载今日统计
 */
const loadTodayStatistics = async (): Promise<void> => {
  try {
    const stats = await verificationApi.getTodayStatistics()
    statistics.value = stats
  } catch (error) {
    console.error('加载统计数据失败:', error)
    
    // 开发阶段：使用模拟数据
    statistics.value = {
      total_verifications: 125,
      pass_count: 108,
      reject_count: 17,
      special_visitor_count: 8,
      my_verifications: 23
    }
  }
}

/**
 * 刷新数据
 */
const refreshData = async (): Promise<void> => {
  await Promise.all([
    loadTodayRecords(),
    loadTodayStatistics()
  ])
  showSuccess('数据已刷新')
}

/**
 * 处理筛选变化
 */
const handleFilterChange = (): void => {
  currentPage.value = 1
}

/**
 * 处理搜索
 */
const handleSearch = (): void => {
  currentPage.value = 1
}

/**
 * 处理分页大小变化
 */
const handleSizeChange = (): void => {
  currentPage.value = 1
}

/**
 * 处理当前页变化
 */
const handleCurrentChange = (): void => {
  // 分页逻辑在计算属性中处理
}

/**
 * 显示记录详情
 * :param record: 核验记录
 */
const showRecordDetail = (record: VerificationRecord): void => {
  selectedRecord.value = record
  detailDialogVisible.value = true
}

/**
 * 生成模拟记录数据
 */
const generateMockRecords = (): VerificationRecord[] => {
  const mockRecords: VerificationRecord[] = []
  const names = ['王小明', '李小红', '张三', '李四', '赵五']
  const hosts = ['李医生', '王护士', '陈主任', '刘大夫']
  const purposes = ['复诊', '体检', '探视', '会诊', '送药']
  
  for (let i = 1; i <= 50; i++) {
    const isPass = Math.random() > 0.2
    const isSpecial = Math.random() > 0.8
    const name = names[Math.floor(Math.random() * names.length)]
    const phone = `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`
    
    const mockRecord: VerificationRecord = {
      id: i,
      visitor_name: name ?? '',
      visitor_phone: phone,
      visitor_id_card: `110101199${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      company: '示例科技有限公司',
      host_name: hosts[Math.floor(Math.random() * hosts.length)] ?? '',
      host_phone: `139${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      visit_time: `2025-09-11T${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:00`,
      purpose: purposes[Math.floor(Math.random() * purposes.length)] ?? '',
      verification_time: `2025-09-11T${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:00`,
      guard_id: authStore.user?.id || 1,
      guard_name: authStore.user?.name || '当前门卫',
      result: isPass ? 'pass' : 'reject',
      rejection_reason: isPass ? '' : '证件信息不符',
      is_special: isSpecial,
      created_at: `2025-09-11T${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:00`
    }
    
    // 只有当是特殊访客时才添加 special_type
    if (isSpecial) {
      mockRecord.special_type = 'VIP'
    }
    
    mockRecords.push(mockRecord)
  }
  
  return mockRecords.sort((a, b) => 
    new Date(b.verification_time).getTime() - new Date(a.verification_time).getTime()
  )
}

/**
 * 组件挂载时初始化数据
 */
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.today-records {
  max-width: 1200px;
  margin: 0 auto;
}

.records-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card-header h2 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.card-header p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.statistics-section {
  margin-bottom: 24px;
  padding: 20px;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
}

.stats-row {
  height: 80px;
}

.stat-item {
  text-align: center;
}

.stat-item :deep(.el-statistic__number) {
  font-size: 28px;
  font-weight: 600;
}

.stat-success :deep(.el-statistic__number) {
  color: var(--el-color-success);
}

.stat-danger :deep(.el-statistic__number) {
  color: var(--el-color-danger);
}

.stat-warning :deep(.el-statistic__number) {
  color: var(--el-color-warning);
}

.stat-suffix {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-left: 4px;
}

.filter-section {
  margin-bottom: 20px;
}

.records-section {
  margin-bottom: 0;
}

.records-table {
  width: 100%;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.record-detail {
  padding: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-row .el-col {
    margin-bottom: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
  
  .records-table {
    font-size: 12px;
  }
}
</style>"